package com.itheima.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.itheima.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class ImageCleanupService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    // 定时任务：每小时执行一次，清理垃圾图片
    @Scheduled(cron = "0 0 * * * ?")
    public void cleanupGarbageImages() {
        SetOperations<String, String> setOps = redisTemplate.opsForSet();

        // 获取 uploaded_images 和 used_images 集合
        Set<String> uploadedImages = setOps.members("uploaded_images");
        Set<String> usedImages = setOps.members("used_images");

        if (uploadedImages != null && usedImages != null) {
            // 计算差集，获取垃圾图片
            Set<String> garbageImages = setOps.difference("uploaded_images", "used_images");

            // 删除阿里云 OSS 中的垃圾图片
            garbageImages.forEach(this::deleteImageFromOSS);

            // 从 Redis 中移除垃圾图片
            setOps.remove("uploaded_images", garbageImages.toArray());
        }
    }

    // 删除阿里云 OSS 中的图片
    private void deleteImageFromOSS(String imageUrl) {
        try {
            // 使用注入的实例调用 delete 方法
            aliOssUtil.delete(imageUrl);
        } catch (Exception e) {
            System.err.println("删除OSS图片失败：" + imageUrl);
            e.printStackTrace();
        }
    }
}